package com.admin.service;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import java.util.regex.Pattern;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.digester.RegexMatcher;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.ibatis.annotations.Param;
import org.dom4j.Branch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.admin.dao.AdminCTSDao;
import com.admin.dao.AdminProjectDao;
import com.admin.dao.AdminSchoolDao;
import com.admin.model.ExcelReadResult;
import com.admin.model.FileMeta;
import com.admin.model.ImportExcelReprotModel;
import com.admin.model.ProjectWithPassCount;
import com.admin.util.AdminProjectExcelTool;
import com.admin.util.AdminTeacherExcelTool;
import com.common.model.AdminUser;
import com.common.model.Department;
import com.common.model.ProfBranch;
import com.common.model.Project;
import com.common.model.StudentUser;
import com.common.model.TeacherUser;
import com.teacher.model.ProjAndProf;

@Service
public class AdminProjectService {
	
	@Autowired
	@Qualifier("adminProjcectDao")
	AdminProjectDao dao;	
	@Autowired
	@Qualifier("adminCTSDao")
	AdminCTSDao ctsDao;
	@Autowired
	@Qualifier("adminSchoolDao")
	AdminSchoolDao schDao;
	/**
	 * 按学院查询所有毕业设计题目
	 * @param clgId
	 * @param start
	 * @return
	 */
	public ArrayList<Project> getAllProjcetsByCollege(int clgId,int page){
		if(page<1){
			page=1;
		}
		int start=(page-1)*10;
		return dao.getAllProjcetsByCollege(clgId, start);
	}
	/**
	 * 按学院查询所有毕业设计数目
	 * @param clgId
	 * @return
	 */
	public int getAllProjcetsCountByCollege(int clgId){
		return dao.getAllProjcetsCountByCollege(clgId);
	}
	/**
	 * 删除一个题目
	 * @param prjId
	 * @return
	 */
	public int deleteProject(int prjId){
		if(prjId==0){
			return 0;
		}
		Project prj=dao.getProjectByPrjId(prjId);
		if(prj==null){
			return 0;
		}
		String commitPath=prj.getCommitmentsPath();
		String essayPath=prj.getEssayPath();
		String attachFilePath=prj.getAttach_file();
		String taskBookPath=prj.getTaskBook();
		HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
		ServletContext context=request.getSession().getServletContext();
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://"
				+ request.getServerName() + ":" + request.getServerPort()
				+ path + "/";
		int basePathLength=basePath.length();
		if(commitPath!=null&&!commitPath.isEmpty()){
			commitPath=context.getRealPath(commitPath.substring(basePathLength));
			File file=new File(commitPath);
			if(file.exists()){
				file.delete();
			}
		}
		if(essayPath!=null&&!essayPath.isEmpty()){
			essayPath=context.getRealPath(essayPath.substring(basePathLength));
			File file=new File(essayPath);
			if(file.exists()){
				file.delete();
			}
		}

		if(attachFilePath!=null&&!attachFilePath.isEmpty()){
			attachFilePath=context.getRealPath(attachFilePath.substring(basePathLength));
			File file=new File(attachFilePath);
			if(file.exists()){
				file.delete();
			}
		}

		if(taskBookPath!=null&&!taskBookPath.isEmpty()){
			taskBookPath=context.getRealPath(taskBookPath.substring(basePathLength));
			File file=new File(taskBookPath);
			if(file.exists()){
				file.delete();
			}
		}
		return dao.deleteProject(prjId);
	}
	/**
	 * 根据题目id获取题目
	 * @param prjId
	 * @return
	 */
	public Project getProjectByPrjId(int prjId){
		return dao.getProjectByPrjId(prjId);
	}
	/**
	 * 修改一个题目
	 * @param prj
	 * @return
	 */
	public int updateProject(Project prj,ArrayList<Integer> branchIdArr){
		dao.updateProject(prj);
		dao.deleteProjectBranchOfPrjId(prj.getId());
		dao.insertProjectBranch(prj.getId(), branchIdArr);
		return 0;
	}
	/**
	 * 删除题目附件,任务书,论文
	 * @param type 1 附件,2任务书,3论文
	 * @param prjId 题目id
	 * @return
	 */
	public int deleteProjectFile(int type,int prjId){
		Project prj=dao.getProjectByPrjId(prjId);
		HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
		ServletContext context=request.getSession().getServletContext();
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://"
				+ request.getServerName() + ":" + request.getServerPort()
				+ path + "/";
		int basePathLength=basePath.length();
		if(type==1){
			String attachFilePath=prj.getAttach_file();
			if(attachFilePath!=null&&!attachFilePath.isEmpty()){
				attachFilePath=context.getRealPath(attachFilePath.substring(basePathLength));
				File file=new File(attachFilePath);
				if(file.exists()){
					file.delete();
				}
			}
			dao.deleteAttachFile(prjId);
		}
		else if(type==2){
			String taskBookPath=prj.getTaskBook();
			if(taskBookPath!=null&&!taskBookPath.isEmpty()){
				taskBookPath=context.getRealPath(taskBookPath.substring(basePathLength));
				File file=new File(taskBookPath);
				if(file.exists()){
					file.delete();
				}
			}
			dao.deleteTaskBook(prjId);
		}else if(type==3){
			String essayPath=prj.getEssayPath();
			if(essayPath!=null&&!essayPath.isEmpty()){
				essayPath=context.getRealPath(essayPath.substring(basePathLength));
				File file=new File(essayPath);
				if(file.exists()){
					file.delete();
				}
			}
			dao.deleteEssay(prjId);
		}
		return 0;
	}
	/**
	 * 修改题目附件,任务书,最终论文
	 * @param file 文件,待上传
	 * @param prjId 题目id
	 * @param type 1 附件,2任务书,3论文
	 */
	public void updateProjectFile(MultipartFile file,int prjId,int type){
		//首先删除之前存在的题目附属文件
		if(file.isEmpty()){
			return;
		}
		deleteProjectFile(type, prjId);
		String fileName="";
		String filePath="";
		String fileExt="";
		String url="";
		int index=file.getOriginalFilename().lastIndexOf(".");
		if(index>-1){
			fileExt=file.getOriginalFilename().substring(index);
		}
		HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
		ServletContext context=request.getSession().getServletContext();
		String rootPath=context.getRealPath("/");
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://"
				+ request.getServerName() + ":" + request.getServerPort()
				+ path + "/";
		if(type==1||type==2){
			SimpleDateFormat sim=new SimpleDateFormat("YYYYMMdd");
			fileName=sim.format(new Date())+RandomUtils.nextInt(10000);
		}else if(type==3){
			Project prj=dao.getProjectByPrjId(prjId);
			if(prj==null){
				return;
			}
			StudentUser stu=ctsDao.getStudentByStuId(prj.getStu_id());
			if(stu==null){
				return;
			}
			fileName=stu.getNo();
		}
		if(type==1){
			filePath="attachFile\\";
		}else if(type==2){
			filePath="taskBook\\";
		}else if(type==3){
			filePath="upload\\student\\";
		}
		File dir=new File(filePath);
		if(!dir.exists()){
			dir.mkdirs();
		}
		//System.out.println(rootPath+filePath+fileName+fileExt);
		try {
			file.transferTo(new File(rootPath+filePath+fileName+fileExt));
		} catch (IllegalStateException e) {
			System.out.println(e.getLocalizedMessage());
		} catch (IOException e) {
			System.out.println(e.getLocalizedMessage());
		}
		url=basePath+filePath+fileName+fileExt;
		url=url.replaceAll("\\\\", "/");
		if(type==1){
			dao.updateAttachFile(url, prjId);
		}else if(type==2){
			dao.updateTaskBook(url, prjId);
		}else if(type==3){
			dao.updateEssay(url, prjId);
		}
	}
	/**
	 * 增加一个题目
	 * @param prj
	 * @param branchIdArr 适用专业列表
	 * @return
	 */
	public int insertProject(Project prj,ArrayList<Integer> branchIdArr){
		dao.insertProject(prj);
		dao.insertProjectBranch(prj.getId(), branchIdArr);
		return 0;
	}
	public int insertProjectByExcel(FileMeta excel,HttpSession session){
		AdminProjectExcelTool projectExcelTool=new AdminProjectExcelTool();
		ExcelReadResult<ImportExcelReprotModel<Project>> result= projectExcelTool.readExcel(excel);
		ExcelReadResult<ImportExcelReprotModel<Project>> error= new ExcelReadResult<>();
		error.setErrorMsg(result.getErrorMsg());
		error.setTotalDataCount(result.getTotalDataCount());
		AdminUser admin=(AdminUser) session.getAttribute("user");
		//致命错误,不导入数据库
		if(result.getErrorMsg()!=null){
			session.setAttribute("projectExcelReadResult", error);
			session.setAttribute("projectExcelReadSuccessCount", 0);
			return 0;
		}
		ArrayList<ImportExcelReprotModel<Project>> dataList=result.getDataList();
		int dataSize=dataList.size();
		int successCount=0;
		//循环导入数据库
		for(int i=0;i<dataSize;i++){
			ImportExcelReprotModel<Project> report=dataList.get(i);
			if(report.errorMsg!=null){
				error.getDataList().add(report);
				report.setErrorLine(i+2);
				continue;//此项数据有错,则这一项就不导入数据库
			}
			Project prj=report.getData();
			//查询指导教师信息
			//首先按工号查询
			TeacherUser tea=ctsDao.getTeacherByTeacherNo(prj.getTeacher().getName());
			if(tea==null){
				//按名字查询
				ArrayList<TeacherUser>teaList=ctsDao.getTeachersByTeacherName(prj.getTeacher().getName());
				if(teaList==null||teaList.size()==0){
					report.setErrorMsg("不存在工号/姓名为:"+prj.getTeacher().getName()+"的教师");
					report.setErrorLine(i+2);
					error.getDataList().add(report);
					continue;
				}else if(teaList.size()>1){
					report.setErrorMsg("存在多个姓名为:"+prj.getTeacher().getName()+"的教师,请输入工号再试");
					report.setErrorLine(i+2);
					error.getDataList().add(report);
					continue;
				}else{
					tea=teaList.get(0);
				}
			}
			if(!admin.isSuperAdmin()&&admin.getCollegeId()!=tea.getDepartment().getCollege().getId()){
				report.setErrorMsg("教师:"+prj.getTeacher().getName()+"不属于您学院,不能添加");
				report.setErrorLine(i+2);
				error.getDataList().add(report);
				continue;
			}
			prj.setTea_id(tea.getId());
			//查询评阅人信息
			//首先按工号查询
			TeacherUser shengyeuTea=ctsDao.getTeacherByTeacherNo(prj.getShengyue_teacher().getName());
			if(shengyeuTea==null){
				//按名字查询
				ArrayList<TeacherUser>shengyueTeaList=ctsDao.getTeachersByTeacherName(prj.getShengyue_teacher().getName());
				if(shengyueTeaList==null||shengyueTeaList.size()==0){
					report.setErrorMsg("不存在工号/姓名为:"+prj.getShengyue_teacher().getName()+"的教师");
					report.setErrorLine(i+2);
					error.getDataList().add(report);
					continue;
				}else if(shengyueTeaList.size()>1){
					report.setErrorMsg("存在多个姓名为:"+prj.getShengyue_teacher().getName()+"的教师,请输入工号再试");
					report.setErrorLine(i+2);
					error.getDataList().add(report);
					continue;
				}else{
					shengyeuTea=shengyueTeaList.get(0);
				}
			}
			if(!admin.isSuperAdmin()&&admin.getCollegeId()!=shengyeuTea.getDepartment().getCollege().getId()){
				report.setErrorMsg("教师:"+prj.getShengyue_teacher().getName()+"不属于您学院,不能添加");
				report.setErrorLine(i+2);
				error.getDataList().add(report);
				continue;
			}
			if(tea.getId()==shengyeuTea.getId()){
				report.setErrorMsg("指导教师与评阅人不能为同一人");
				report.setErrorLine(i+2);
				error.getDataList().add(report);
				continue;
			}
			prj.setShengyue_tea_id(shengyeuTea.getId());
			//适用专业
			ArrayList<Integer>branchArr=new ArrayList<>();
			StringBuffer errorBranchString=new StringBuffer();
			for (ProjAndProf pap : prj.getProfs()) {//循环读取所有适用专业
				if(pap.getBranch().getName().isEmpty()){
					continue;
				}
				ArrayList<ProfBranch> branchList=schDao.getProBranchByPbName(pap.getBranch().getName());
				if(branchList==null||branchList.size()==0){//不存在
					errorBranchString.append("专业方向:").append(pap.getBranch().getName()).append("不存在");
					break;
				}
				if(branchList.size()>1){//重复
						errorBranchString.append("存在多个同名专业方向:").append(pap.getBranch().getName()).append(".分别位于<br/>");
						for (ProfBranch profBranch : branchList) {
							errorBranchString.append(profBranch.getProf().getDepartment().getCollege().getName()).append(">");
							errorBranchString.append(profBranch.getProf().getDepartment().getName()).append(">");
							errorBranchString.append(profBranch.getProf().getName()).append("<br/>");
						}
						if(errorBranchString.length()>"<br/>".length()){
							errorBranchString.setLength(errorBranchString.length()-"<br/>".length());
						}
					break;
				}
				ProfBranch branch=branchList.get(0);
				//无权限
				if(!admin.isSuperAdmin()&&branch.getProf().getDepartment().getCollegeId()!=admin.getCollegeId()){
					errorBranchString.append("专业方向:"+branch.getName()+"不属于您学院,不能添加");
					break;
				}
				if(!branchArr.contains(branch.getId())){
					branchArr.add(branchList.get(0).getId());
				}
			}
			if(errorBranchString.length()>0){
				report.setErrorMsg(errorBranchString.toString());
				report.setErrorLine(i+2);
				error.getDataList().add(report);
				continue;
			}
			if(branchArr.size()==0){
				report.setErrorMsg("请至少选择一个专业方向");
				report.setErrorLine(i+2);
				error.getDataList().add(report);
				continue;
			}
			try{
				dao.insertProject(prj);
				dao.insertProjectBranch(prj.getId(), branchArr);
			}catch(Exception e){
				e.printStackTrace();
				report.setErrorMsg("参数错误,请检查");
				report.setErrorLine(i+2);
				error.getDataList().add(report);
				continue;
			}
			successCount++;
		}
		session.setAttribute("projectExcelReadResult", error);
		session.setAttribute("projectExcelReadSuccessCount", successCount);
		return 0;
	}
	/**
	 * 查询所有题目
	 * @return
	 */
	public ArrayList<Project>getAllProject(){
		return dao.getAllProject();
	}
	/**
	 * 通过学院获得所有未通过的题目(用于普通管理员)
	 * @param clgId 学院id
	 * @param start
	 * @return
	 */
	public  ArrayList<ProjectWithPassCount> getUnAutoProjectByCollege(int clgId,int page){
		if(page<1){
			page=1;
		}
		int start=(page-1)*10;
		ArrayList<Project> prjList=dao.getUnAutoProjectByCollege(clgId, start);
		ArrayList<ProjectWithPassCount> prjCList=new ArrayList<>();
		for (Project prj : prjList) {
			ProjectWithPassCount prjC=new ProjectWithPassCount();
			prjC.setPrj(prj);
			prjC.setPassCount(dao.getPassPrjCountOfTea(prj.getTeacher().getId()));
			prjCList.add(prjC);
		}
		return prjCList;
	}
	public  int getUnAutoProjectCountByCollege(int clgId){
		return dao.getUnAutoProjectCountByCollege(clgId);
	}
	/**
	 * 获取所有未通过的题目(用于超级管理员)
	 * @param start
	 * @return
	 */
	public  ArrayList<ProjectWithPassCount> getUnAutoProjectByAll(int page){
		if(page<1){
			page=1;
		}
		int start=(page-1)*10;	
		ArrayList<Project> prjList=dao.getUnAutoProjectByAll(start);
		ArrayList<ProjectWithPassCount> prjCList=new ArrayList<>();
		for (Project prj : prjList) {
			ProjectWithPassCount prjC=new ProjectWithPassCount();
			prjC.setPrj(prj);
			prjC.setPassCount(dao.getPassPrjCountOfTea(prj.getTeacher().getId()));
			prjCList.add(prjC);
		}
		return prjCList;
	}
	public  int getUnAutoProjectCountByAll(){
		return dao.getUnAutoProjectCountByAll();
	}
	public int failProject(int prjId,String failReason){
		return dao.failProject(prjId, failReason);
	}
	/**
	 * 批量通过审核题目
	 * @param prjIdList
	 * @return
	 */
	public void passProject(ArrayList<Integer> prjIdList){
		dao.passProject(prjIdList);
	}
}
